package com.lv.suyiyong.hfr.fragment

import android.os.Bundle
import android.view.View
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SizeUtils
import com.lv.common.base.BaseFragment
import com.lv.common.bean.CommonSelectedBean
import com.lv.common.ktx.LoadSrc
import com.lv.common.ktx.initSingleClickListener
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.CountDownUtil
import com.lv.service.adapter.ViewPager2ComAdapter
import com.lv.service.bean.GoodsItemBean
import com.lv.service.bean.HomeTopBean
import com.lv.service.bean.TelSecondCategory
import com.lv.service.dialog.CategoryImagePopupView
import com.lv.service.model.EditorViewModel
import com.lv.service.model.ServiceViewModel
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onFailure
import com.lv.service.network.onSuccess
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.adapter.BannerHomeBrandAdapter
import com.lv.suyiyong.hfr.adapter.SpecialScrollChildAdapter
import com.lv.suyiyong.hfr.databinding.FragmentHomeGoodsBinding
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupPosition
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.withContext
import org.koin.androidx.viewmodel.ext.android.viewModel


/**
 * 作者： ygx
 * 创建日期：2023/2/10 11:24 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：应用商城需要的权限：ABCDEFGHIJKLMNO
 */
class HomeGoodsFragment : BaseFragment(), View.OnClickListener {
    private val mCategoryBeans = mutableListOf<CommonSelectedBean>()
    private val mCategoryPopBeans = mutableListOf<TelSecondCategory>()
    private var mTabAdapter: ViewPager2ComAdapter? = null
    private val mEditorViewModel: EditorViewModel by activityViewModels()
    private var mFcaid = 0
    private var mBrandBannerAdapter: BannerHomeBrandAdapter? = null
    private var mLocationBannerAdapter: BannerHomeBrandAdapter? = null
    private var mHotAdapter: BannerHomeBrandAdapter? = null
    private var mWholeAdapter: BannerHomeBrandAdapter? = null
    private var mYHAdapter: SpecialScrollChildAdapter? = null
    private val mBrandBeans = mutableListOf<List<GoodsItemBean>>()
    private val mLocationBeans = mutableListOf<List<GoodsItemBean>>()
    private val mWholeBeans = mutableListOf<List<GoodsItemBean>>()
    private val mHotBanners = mutableListOf<List<GoodsItemBean>>()
    private val mYHBanners = mutableListOf<GoodsItemBean>()
    private var mTimer: CountDownUtil? = null
    private val viewModelService: ServiceViewModel by viewModel()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    private var mBinding: FragmentHomeGoodsBinding? = null

    override fun getLayoutRes() = R.layout.fragment_home_goods
    override fun bindView(view: View, savedInstanceState: Bundle?): ViewDataBinding {
        mBinding = FragmentHomeGoodsBinding.bind(view).apply {
            initSingleClickListener(clBrand, ivMore, clNear, clHot, clWhole)
        }

        return mBinding!!
    }

    override fun initConfig() {
        super.initConfig()
        mBinding?.ivTagBrand?.LoadSrc("https://suyiyong.oss-cn-hangzhou.aliyuncs.com/iOS/projectPic/hfr/home_twoCard0.png")
        mBinding?.ivTagNear?.LoadSrc("https://suyiyong.oss-cn-hangzhou.aliyuncs.com/iOS/projectPic/hfr/home_twoCard1.png")
        mBinding?.ivTagHot?.LoadSrc("https://suyiyong.oss-cn-hangzhou.aliyuncs.com/iOS/projectPic/hfr/home_twoCard2.png")
        mBinding?.ivTagWhole?.LoadSrc("https://suyiyong.oss-cn-hangzhou.aliyuncs.com/iOS/projectPic/hfr/home_twoCard3.png")
        initBannerAdapter()
        homePage()
        mEditorViewModel.liveSpuCategoryData.observeKt { mCategorys ->
            mCategoryBeans.clear()
            mCategoryPopBeans.clear()
            mCategoryBeans.add(CommonSelectedBean("推荐", "", true))
            mCategorys?.forEach { categoryItem ->
                val telSecondCategory = TelSecondCategory(
                    categoryItem.fcaid, categoryItem.id, categoryItem.image, categoryItem.name,
                    0, 0, null, false, true
                )
                mCategoryPopBeans.add(telSecondCategory)
                mCategoryBeans.add(
                    CommonSelectedBean(
                        categoryItem.name, "${categoryItem.fcaid}"
                    )
                )
                val telSecondCategories = categoryItem.telSecondCategories
                telSecondCategories?.let { mCategoryPopBeans.addAll(it) }
            }
            initPage()
        }
    }

    private fun initPage() {
        initViewPager()
    }

    private fun initViewPager() {

        mTabAdapter = ViewPager2ComAdapter(
            childFragmentManager, lifecycle, mCategoryBeans,
            object : ViewPager2ComAdapter.TabPagerListener {
                override fun getFragment(position: Int): Fragment {
                    return HomeSpuCategoryFragment.newInstance(mCategoryBeans[position])
                }

            }
        )
        mBinding?.viewPager?.adapter = mTabAdapter
        mBinding?.viewPager?.offscreenPageLimit = mCategoryBeans.size

        mBinding?.ygxIndicator?.setViewPager(mBinding?.viewPager, mCategoryBeans)
        mBinding?.ygxIndicator?.setOnPageChangeListener(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                var fac = mCategoryBeans[position].tag
                if (fac.isEmpty()) {
                    fac = "0"
                }
                try {
                    mFcaid = fac.toDouble().toInt()
                } catch (e: Exception) {
                    mFcaid = 0
                }
            }
        })

    }

    private fun homePage() {
        val homePageMap = mutableMapOf("code" to "1", "province" to "湖北省")
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                withContext(myScope.coroutineContext) {
                    viewModelService.homePage(homePageMap)
                }
            parseHomePageResult(result)
        }
    }

    private fun parseHomePageResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<HomeTopBean> { code, data, message, result ->
                val brand = data?.brand
                val brands = brand?.chunked(2)
                mBrandBeans.clear()
                brands?.let { mBrandBeans.addAll(it) }
                mBrandBannerAdapter?.notifyDataSetChanged()
//
                val nearby = data?.nearby
                val nearbys = nearby?.chunked(2)
                mLocationBeans.clear()
                nearbys?.let { mLocationBeans.addAll(it) }
                mLocationBannerAdapter?.notifyDataSetChanged()
//
                val hot = data?.hot
                mHotBanners.clear()
                val hots = hot?.chunked(2)
                hots?.let { mHotBanners.addAll(it) }
                mHotAdapter?.notifyDataSetChanged()

                val batch = data?.batch
                val batchs = batch?.chunked(2)
                mWholeBeans.clear()
                batchs?.let { mWholeBeans.addAll(it) }
                mWholeAdapter?.notifyDataSetChanged()

                val favorable = data?.favorable
                mYHBanners.clear()
                favorable?.let { mYHBanners.addAll(it) }
                favorable?.let { mYHBanners.addAll(it) }
                favorable?.let { mYHBanners.addAll(it) }
                favorable?.let { mYHBanners.addAll(it) }
                mYHAdapter?.notifyDataSetChanged()
                mBinding?.rvYh?.postDelayed({
                    mBinding?.rvYh?.handleTimeHandler(true)
                }, 200)
                val endtime = data?.endtime ?: 0L
                val currentTimeMillis = System.currentTimeMillis()
                val time = (endtime - currentTimeMillis) / 1000
                if (time > 0) {
                    initTimer(time)
                }
//              timer
            }
            onBizError<Any> { code, message, data ->
            }
        }
        data.onFailure {
        }
    }

    /**
     * 初始化轮播图Adapter
     */
    private fun initBannerAdapter() {
        mBrandBannerAdapter = BannerHomeBrandAdapter(mBrandBeans)
        mBinding?.bannerBrand?.adapter = mBrandBannerAdapter
        mBinding?.bannerBrand?.setIntercept(true)
        mLocationBannerAdapter = BannerHomeBrandAdapter(mLocationBeans)
        mBinding?.bannerNear?.adapter = mLocationBannerAdapter
        mBinding?.bannerNear?.setIntercept(true)
        mHotAdapter = BannerHomeBrandAdapter(mHotBanners, 1)
        mBinding?.bannerHot?.adapter = mHotAdapter
        mBinding?.bannerHot?.setIntercept(true)
        mWholeAdapter = BannerHomeBrandAdapter(mWholeBeans, 2)
        mBinding?.bannerWhole?.adapter = mWholeAdapter
        mBinding?.bannerWhole?.setIntercept(true)
        mYHAdapter = SpecialScrollChildAdapter(requireContext(), mYHBanners)
        mBinding?.rvYh?.adapter = mYHAdapter

    }

    override fun initData() {
        super.initData()

    }


    override fun initEvents() {
        super.initEvents()

//        rigestEventBus()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_more -> {//更多分类
                showCategoryPop()
            }

            R.id.cl_brand -> {//品牌热卖
                ARouter.getInstance().build(ARoutUtils.BrandHotSalerActivity).navigation()
            }

            R.id.cl_near -> {//附近商品
                ARouter.getInstance().build(ARoutUtils.NearGoodsTabActivity).navigation()
            }

            R.id.cl_hot -> {//热销
                ARouter.getInstance().build(ARoutUtils.HotSalerTabActivity).navigation()
            }

            R.id.cl_whole -> {//批发
                ARouter.getInstance().build(ARoutUtils.WholeSalerActivity).navigation()
            }
        }
    }

    //    private var mCategoryPopupView: CategoryImagePopupView? = null
    private fun showCategoryPop() {
        val topH = SizeUtils.dp2px(200.0f)
        var mCategoryPopupView = CategoryImagePopupView(
            requireContext(), "全部分类", mCategoryPopBeans, topH,
            { position, datas -> })
        XPopup.Builder(requireContext())
            .isViewMode(true)//对于只使用一次的弹窗，推荐设置这个true
            .popupPosition(PopupPosition.Bottom)
            .asCustom(mCategoryPopupView)
            .show()
        mCategoryPopupView.scrollID(mFcaid)
    }

    private fun initTimer(endTime: Long) {
        mTimer = CountDownUtil()
        val time_pay = System.currentTimeMillis()
        mTimer?.start(
            time_pay, endTime,
            CountDownUtil.COUTDOWN.TIME_S,
            object : CountDownUtil.OnCountDownCallBack {
                override fun onProcess(day: Int, hour: Int, minute: Int, second: Int) {
                    val dayFormat = String.format("%02d", day)
                    val hourFormat = String.format("%02d", hour)
                    val minuteFormat = String.format("%02d", minute)
                    val secondFormat = String.format("%02d", second)
                    mBinding?.tvD?.text = "$dayFormat"
                    mBinding?.tvH?.text = "$hourFormat"
                    mBinding?.tvM?.text = "$minuteFormat"
                    mBinding?.tvS?.text = "$secondFormat"

                }

                override fun onFinish() {

                }
            })
    }

    companion object {
        @JvmStatic
        fun newInstance() = HomeGoodsFragment()
    }

    override fun onResume() {
        super.onResume()
        LogUtils.e("onResume")
    }


    override fun onDestroy() {
        super.onDestroy()
        if (mTimer != null) {
            mTimer?.onDestroy()
            mTimer = null
        }
    }

}